/*
 * @(#)SysUserController.java 1.0 2019年10月31日下午1:30:49
 *
 * Saturn Framework Co.Limt
 * Copyright (c) 2012-2019 tanks, Inc. All rights reserved.
 */
package com.saturn.config.server.web;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saturn.config.server.base.dto.JsonResult;
import com.saturn.config.server.base.entity.SysUser;
import com.saturn.config.server.service.SysUserService;
import com.saturn.config.server.util.EncryptUtils;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <dl>
 *    <dt><b>Title:</b></dt>
 *    <dd>
 *    	none
 *    </dd>
 *    <dt><b>Description:</b></dt>
 *    <dd>
 *    	<p>none
 *    </dd>
 * </dl>
 *
 * @author tanks
 * @version 1.0, 2019年10月31日
 * @since config-center-admin
 * 
 */
@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/sysuser")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SysUserController {

	private SysUserService sysUserService;
	
	/**
	 * 分页查询
	 * @param page    分页对象
	 * @param appInfo 应用信息表
	 * @return
	 */
	@RequestMapping(value = "/page", produces = "application/json")
	public @ResponseBody IPage<?> queryPage(HttpServletRequest request, Page page, SysUser sysUser) {
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		if (StringUtils.isBlank(start)) {
			page.setCurrent(Long.parseLong(start));
		} else {
			page.setCurrent(1l);
		}
		if (StringUtils.isBlank(limit)) {
			page.setSize(Long.parseLong(limit));
		} else {
			page.setSize(20l);
		}
		if( StringUtils.EMPTY.equals(sysUser.getUserName()) ) {
			sysUser.setUserName(null);
		}
		return sysUserService.page(page, Wrappers.query(sysUser));
	}
	
	/**
	 * 新增用户
	 * @param appConfig 应用配置项
	 * @return R
	 */
	@RequestMapping(value = "/save", produces = "application/json")
	public @ResponseBody JsonResult save(HttpServletRequest request,SysUser sysUser) throws Exception{
		SysUser loginUser = (SysUser)request.getSession().getAttribute("useInfo");
		if( !"A".equals(loginUser.getType())) {
			JsonResult result = new JsonResult();
			result.setSuccess(Boolean.FALSE.booleanValue());
			result.setRespMsg("无权限访问,保存失败!");
			return result;
		}
		sysUser.setCreateTime(LocalDateTime.now());
		sysUser.setPassword(EncryptUtils.md5Digest(sysUser.getPassword()));
		JsonResult result = new JsonResult();
		boolean op = this.sysUserService.save(sysUser);
		result.setSuccess(op);
		result.setRespMsg(op ? "保存成功！":"保存失败!");
		return result;
	}
	
	/**
	 * 批量数据删除
	 * @return
	 */
	@RequestMapping(value = "/delete",produces="application/json")
	public @ResponseBody JsonResult deleteRecord(HttpServletRequest request,@RequestParam("userIds") String[] userIds) {
		SysUser loginUser = (SysUser)request.getSession().getAttribute("useInfo");
		if( !"A".equals(loginUser.getType())) {
			JsonResult result = new JsonResult();
			result.setSuccess(Boolean.FALSE.booleanValue());
			result.setRespMsg("无权限访问,保存失败!");
			return result;
		}
		JsonResult response = new JsonResult();
		if( userIds==null || userIds.length==0 ){
			response.setSuccess(Boolean.FALSE.booleanValue());
			response.setRespMsg("删除失败！");
		}
		try{
			List<String> ids = new ArrayList<String>();
			for(String userId:userIds) {
				ids.add(userId);
			}
			int size = this.sysUserService.deleteRecords(ids);
			if( size>0 ){
				response.setSuccess(Boolean.TRUE.booleanValue());
				response.setRespMsg("删除成功,总共" + size + "条记录！");
			}else{
				response.setSuccess(Boolean.FALSE.booleanValue());
				response.setRespMsg("删除失败！");
			}
		}catch(Exception ex){
			log.error("失败",ex);
			response.setSuccess(Boolean.FALSE.booleanValue());
			response.setRespMsg("操作失败");
		}
		return response;
	}
	
	/** 
	 * 批量保存数据
	 * @param request
	 * @return
	 * @throws BusinessException
	 */
	@RequestMapping(value = "batchRecords",produces="application/json")
	public @ResponseBody JsonResult batchRecords(HttpServletRequest request) {
		SysUser loginUser = (SysUser)request.getSession().getAttribute("useInfo");
		if( !"A".equals(loginUser.getType())) {
			JsonResult result = new JsonResult();
			result.setSuccess(Boolean.FALSE.booleanValue());
			result.setRespMsg("无权限访问,保存失败!");
			return result;
		}
		JsonResult response = new JsonResult();
		String jsonText = request.getParameter("datas");
		List<SysUser> sysUsers = JSONObject.parseArray(jsonText, SysUser.class);
		try{
			int size = this.sysUserService.batchSaveRecords(sysUsers);
			if( size>0 ){
				response.setSuccess(Boolean.TRUE.booleanValue());
				response.setRespMsg("保存数据成功，更新记录数【" + size + "】条！");
			}else{
				response.setSuccess(Boolean.FALSE.booleanValue());
				response.setRespMsg("保存数据失败！");
			}
		}catch(Exception ex){
			log.error("失败",ex);
			response.setSuccess(Boolean.FALSE.booleanValue());
			response.setRespMsg("保存数据失败");
		}
		return response;
	}
}
